package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.DatePicker.DatePicker;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.PreparePregnantBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import demo.cn.addapp.pickers.listeners.OnItemPickListener;
import demo.cn.addapp.pickers.listeners.OnSingleWheelListener;
import demo.cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 22.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 */
public class PreparePregnantActivity extends Activity {
    private static final String TAG = "PreparePregnantActivity";
    @Bind(R.id.activity_prepare_pregnant_rl_iv_return)
    ImageView activityPreparePregnantRlIvReturn;
    @Bind(R.id.activity_prepare_pregnant_bt_determine)
    Button activityPreparePregnantBtDetermine;
    @Bind(R.id.activity_prepare_pregnant_tv_date_of_last_menstrual_period)
    TextView activityPreparePregnantTvDateOfLastMenstrualPeriod;
    @Bind(R.id.activity_prepare_pregnant_rl_date_of_last_menstrual_period)
    RelativeLayout activityPreparePregnantRlDateOfLastMenstrualPeriod;
    @Bind(R.id.activity_prepare_pregnant_tv_Number_of_days_during_menstrual_cycle)
    TextView activityPreparePregnantTvNumberOfDaysDuringMenstrualCycle;
    @Bind(R.id.activity_prepare_pregnant_rl_Number_of_days_during_menstrual_cycle)
    RelativeLayout activityPreparePregnantRlNumberOfDaysDuringMenstrualCycle;
    @Bind(R.id.activity_prepare_pregnant_tv_Menstrual_days)
    TextView activityPreparePregnantTvMenstrualDays;
    @Bind(R.id.activity_prepare_pregnant_rl_Menstrual_days)
    RelativeLayout activityPreparePregnantRlMenstrualDays;


    private Calendar calendar = Calendar.getInstance();
    private  final int mYear = calendar.get(Calendar.YEAR); // 获取当前年份
    private  final int mMonth = calendar.get(Calendar.MONTH) + 1;// 获取当前月份
    private  final int mday = calendar.get(Calendar.DAY_OF_MONTH); // 获取当日


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prepare_pregnant);
        ButterKnife.bind(this);

        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);
    }

    @OnClick({R.id.activity_prepare_pregnant_rl_iv_return, R.id.activity_prepare_pregnant_bt_determine,
            R.id.activity_prepare_pregnant_tv_date_of_last_menstrual_period, R.id.activity_prepare_pregnant_rl_Number_of_days_during_menstrual_cycle,
            R.id.activity_prepare_pregnant_rl_Menstrual_days})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_prepare_pregnant_rl_iv_return:
                Intent intent5 = new Intent(PreparePregnantActivity.this, MyStateActivity.class);
                startActivity(intent5);
                finish();
                break;
            case R.id.activity_prepare_pregnant_bt_determine:
               String numberOfDaysDuringMenstrualCycle =  activityPreparePregnantTvNumberOfDaysDuringMenstrualCycle.getText().toString().trim();
                if(!TextUtils.isEmpty(numberOfDaysDuringMenstrualCycle)){
                    String menstrualDays =  activityPreparePregnantTvMenstrualDays.getText().toString().trim();
                    if(!TextUtils.isEmpty(menstrualDays)){
                        String dateOfLastMenstrualPeriod =  activityPreparePregnantTvDateOfLastMenstrualPeriod.getText().toString().trim();
                        if(!TextUtils.isEmpty(dateOfLastMenstrualPeriod)){
                            subimtPreparePregnant(numberOfDaysDuringMenstrualCycle,menstrualDays,dateOfLastMenstrualPeriod);
                        }else{
                            Toast.makeText(PreparePregnantActivity.this, "请选择末次月经日期", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(PreparePregnantActivity.this, "请选择月经天数", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(PreparePregnantActivity.this, "请选择月经周期天数", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.activity_prepare_pregnant_tv_date_of_last_menstrual_period: //末次月经日期
                lastMenstrualPeriod();
                break;
            case R.id.activity_prepare_pregnant_rl_Number_of_days_during_menstrual_cycle:   //月经周期天数
                duringMenstrualCycle();
                break;
            case R.id.activity_prepare_pregnant_rl_Menstrual_days:
                menstrualDay();
                break;
        }
    }
    /**
     * @desc 提交备孕信息
     * */
    private void subimtPreparePregnant(String numberOfDaysDuringMenstrualCycle, String menstrualDays, String dateOfLastMenstrualPeriod) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CHANGE_PREPARE_PREGNANT)
                .addParams("cus_id", user_id)
                .addParams("menses_date", dateOfLastMenstrualPeriod)
                .addParams("menses_period",menstrualDays)
                .addParams("menses_day",numberOfDaysDuringMenstrualCycle)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final PreparePregnantBean preparePregnantBean =   gson.fromJson(praiseParseNetworkResponse,PreparePregnantBean.class);
                        if(preparePregnantBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"备孕信息修改成功",Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            });
                        }else {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),preparePregnantBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 月经周期天数选择项
     * @desc 月经周期天数范围在(22天--->40天)
     * */
    private void duringMenstrualCycle() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 22; i < 41; i++) {
            list.add(i + " 天");
        }
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(6);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setLabel("");
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {
            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                String[] split = item.split(" ");
                String mm = split[0];
                activityPreparePregnantTvNumberOfDaysDuringMenstrualCycle.setText(mm);
            }
        });
        picker.show();
    }
    /**
     * @desc 月经天数
     * @desc 月经天数范围在(2天--->14天)
     * @dec select_menstrual_day 选择月经天数
     * */
    private void menstrualDay() {
        ArrayList<String> list = new ArrayList<>();
        for(int i = 2;i<15; i++){
            list.add(i+" 天");
        }
        //        String[] ss = (String[]) list.toArray();
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(8);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setLabel("");
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {
            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                String[] split = item.split(" ");
                String mm = split[0];
                activityPreparePregnantTvMenstrualDays.setText(mm);
            }
        });
        picker.show();
    }

    /**
     * @desc 末次月经日期
     * @desc 末次月经日期 (最大是今天，然后是往前推40天)
     * @desc select_menstrual_period 选择末次月经日期
     * */
    private void lastMenstrualPeriod() {

        DatePicker picker = new DatePicker(this);
        picker.setRange(2000, 2030);
        picker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                int yearint = Integer.parseInt(year);
                int monthint = Integer.parseInt(month);
                int dayint = Integer.parseInt(day);
                if(yearint == mYear){
                    if(monthint == mMonth ){
                        if(dayint <= mday){
                            activityPreparePregnantTvDateOfLastMenstrualPeriod.setText(year + "-" + month + "-" + day);
                        }else{
                            Toast.makeText(PreparePregnantActivity.this, "你的选择超出末次月经日期不在有效时间范围内", Toast.LENGTH_SHORT).show();
                        }
                    }else  if(monthint < mMonth  && monthint > mMonth-2){
                        activityPreparePregnantTvDateOfLastMenstrualPeriod.setText(year + "-" + month + "-" + day);
                    }else if(monthint == mMonth-2){
                        activityPreparePregnantTvDateOfLastMenstrualPeriod.setText(year + "-" + month + "-" + (30+dayint-10));
                    }else{
                        Toast.makeText(PreparePregnantActivity.this, "你的选择超出末次月经日期不在有效时间范围内", Toast.LENGTH_SHORT).show();
                    }
                }else if(yearint == mYear-1){
                    if(monthint > mMonth && (monthint - mMonth)<= 2){
                        if(mMonth < 3 && monthint > 10){
                            activityPreparePregnantTvDateOfLastMenstrualPeriod.setText(year + "-" + month + "-" + day);
                        }else{
                            Toast.makeText(PreparePregnantActivity.this, "你的选择超出末次月经日期不在有效时间范围内", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(PreparePregnantActivity.this, "你的选择超出末次月经日期不在有效时间范围内", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(PreparePregnantActivity.this, "你的选择超出末次月经日期不在有效时间范围内", Toast.LENGTH_SHORT).show();
                }
            }
        });
        picker.show();
    }
}
